Page({
  data: {
    showCount: false,
    mobile: '17634534419',
    code: '246810',
    timeData: '',
    backTo: '',
  },

  onLoad(res) {
    this.setData({
      backTo: res.backTo,
    })
    console.log(res)
  },
  onShow() {
    console.log('111333')
  },
  onChange(ev) {
    console.log(ev.detail)
    this.setData({
      timeData: ev.detail,
      showCount: ev.detail.minutes === 1 || ev.detail.seconds === 0,
    })
  },
  validateMobile() {
    const reg = /^1[3-9]\d{9}$/
    const flag = reg.test(this.data.mobile)
    if (!flag) wx.utils.toast('手机号格式错误！')
    return flag
  },
  validateCode() {
    const reg = /^\d{6}$/
    const flag = reg.test(this.data.code)
    if (!flag) wx.utils.toast('验证码格式错误！')
    return flag
  },

  //发送验证码
  async getCode() {
    if (!this.validateMobile()) return
    const res = await wx.http.get(`/v1_0/sms/codes/${this.data.mobile}`)
    console.log(res)
    this.setData({
      showCount: true,
    })
  },
  //登录
  async submitForm() {
    if (!this.validateMobile()) return
    if (!this.validateCode()) return
    const { mobile, code } = this.data
    const {
      data: { token, refresh_token },
    } = await wx.http.post('/v1_0/authorizations', { mobile, code })
    console.log(token)
    getApp().setToken(token, refresh_token)
    const url = this.data.backTo
    console.log(url, '11111')
    wx.redirectTo({
      url: this.data.backTo,
    })

    // wx[url === '/pages/index/index' ? 'switchTab' : 'redirectTo']({ url })
  },
})
